﻿using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Services;
using NPOI.SS.Formula.Functions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Yitter.IdGenerator;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace CoreShop.App
{
    public partial class frmFoodgroupOptional : UIForm
    {
        private List<corecmsfoodordering> packdetailList = null;
        //配菜组列表
        private List<corecmsfooddetailgroup> detailgroupList = null;
        //分组详细
        private List<corecmsfoodgroupdetail> foodGroupdetailList = null;
        public corecmsfoodordering orderingParent;

        public frmFoodgroupOptional()
        {
            InitializeComponent();
        }

        private void frmfoodgroup_Load(object sender, EventArgs e)
        {
            lblFoodName.Text = "配菜：" + orderingParent.name;
            detailgroupList = new corecmsfooddetailgroupServices().GetList(p => p.foodId == orderingParent.foodId && p.isDelete == false);
            packdetailList = new corecmsfoodorderingServices().GetListByFoodGroupdetailId(orderingParent);
            if (packdetailList.Count == 0)
            {
                ShowInfoTip("没有配菜明细,无法选择。");
                btnOk.Visible = false;
                return;
            }
            BindFoodList();
        }

        private void BindFoodList()
        {
            layFoodList.Visible = false;
            layFoodList.Clear();
            string packGroupName = "";
            btnOk.Enabled = (detailgroupList.Sum(p => p.minQuantity.Value) == 0);
            foreach (var item in detailgroupList)
            {
                string selectTypeName = EnumHelper.GetDescByValue<GlobalEnumVars.FoodGroupSelectType>(item.selectType);
                string packName = packdetailList.Find(p => p.packGroupId == item.groupId).packGroupName;
                if (string.IsNullOrEmpty(packName)) packName = item.id.ToString();
                var packGroup = packdetailList.Where(p => p.packGroupId == item.groupId).ToList();
                //if (item.selectType == 1)
                //{
                //    item.minQuantity = 1; item.maxQuantity = packGroup.Count;
                //}



                if (item.selectType == 1)
                    packGroupName = string.Format("{0} ---(说明:{1})", packName, selectTypeName, item.minQuantity, item.maxQuantity);
                else if (item.selectType == 2)
                    packGroupName = string.Format("{0} ---(说明:{1}{2}项)", packName, selectTypeName, item.minQuantity);
                else packGroupName = string.Format("{0} ---(说明:{1},选择{2}~{3}项)", packName, selectTypeName, item.minQuantity, item.maxQuantity);
                if (string.IsNullOrEmpty(packGroupName)) packGroupName = item.id.ToString();
                AddType(packGroupName);

                //if (item.selectType == 2 && packGroup.Count == item.minQuantity)
                //    packGroup.ForEach(p => p.itemCount = 1);
                int rows = CommFunc.ConvertToInt32(Math.Ceiling(packGroup.Count / 5.0));
                AddGroupItems(packGroupName, packGroup, item);
            }
            layFoodList.Visible = true;
        }

        public void AddType(string type)
        {
            UIMenuItemSeparator item = new UIMenuItemSeparator(type, 40);
            item.SetOtherMode();
            item.Width = layFoodList.Width - 30;
            layFoodList.Add(item);
        }

        public void AddGroupItems(string packTypeName, List<corecmsfoodordering> items, corecmsfooddetailgroup packItem)
        {
            var maxPriceItem = items.OrderByDescending(p => p.price).First();
            foreach (var item in items)
            {
                if (packItem.selectType != 2 || (packItem.selectType == 2 && packItem.collectType == 2 && item.foodSpecId != maxPriceItem.foodSpecId))
                {
                    item.price = 0;
                    item.allAmount = 0;
                    item.amount = 0;
                    item.realPrice = 0;
                    item.realAmount = 0;
                    item.discount = 1;
                }
                string price = string.Format("￥{0}", item.price.ToString("0.##"));
                var info = new UAddFoodItemInfo(packTypeName, item.name, price, item.itemCount, item.rowId.ToString());
                if (!packItem.isSelectSame)
                    info.MaxCount = 1;

                AddFoods(info);
            }
        }

        public void AddFoods(UAddFoodItemInfo info)
        {
            UIAddFoodsItem item = new UIAddFoodsItem();
            item.Tag = info.ItemId;
            item.Type = info.Type;
            item.Food = info.Food;
            item.Money = info.Money;
            item.Count = info.Count;
            item.MaxCount = info.MaxCount;
            item.OnValueChanged += FoodsItem_OnValueChanged;
            item.OnAddValueError += FoodsItem_OnAddValueError;
            layFoodList.Add(item);
        }

        private void FoodsItem_OnValueChanged(object sender, System.EventArgs e)
        {
            UIAddFoodsItem info = (UIAddFoodsItem)sender;
            int number = info.Count;
            int rowId = CommFunc.ConvertToInt32(info.Tag);
            var packdetail = packdetailList.Find(p => p.rowId == rowId);
            if (packdetail == null)
            {
                UIMessageBox.Show("选择失败，选择的明细未能找到。", "系统出错:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            int addNumber = number - packdetail.itemCount;
            long packGroupId = packdetail.packGroupId;
            var itemSum = packdetailList.Where(p => p.packGroupId == packGroupId).Sum(p => p.itemCount) + addNumber;
            if (packdetail.packGroupQuantity > 0 && itemSum > packdetail.packGroupQuantity)
            {
                info.Count = packdetail.itemCount;
                string msg = string.Format("本组选择的数量不能超过{0}", packdetail.packGroupQuantity);
                ShowErrorTip(msg);
                return;
            }
            packdetail.itemCount = number;
            ///判断是否可以提交
            bool canSubmit = true;
            foreach (var gItem in detailgroupList)
            {
                var packdetailselectCount = packdetailList.Where(p => p.packGroupId == gItem.groupId).Sum(p => p.itemCount);
                if (packdetailselectCount < gItem.minQuantity)
                {
                    canSubmit = false; break;
                }
            }

            btnOk.Enabled = canSubmit;
        }

        private void FoodsItem_OnAddValueError(object sender, System.EventArgs e)
        {
            UIAddFoodsItem info = (UIAddFoodsItem)sender;
            int maxNumber = info.MaxCount;
            string msg = string.Format("选择的数量不能超过{0}", maxNumber);
            ShowErrorTip(msg);
        }

        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            //数量归零，重新计算
            foreach (var item in packdetailList)
            {
                item.itemCount = 0;
            }

            List<corecmsfoodordering> packdetail_save = new List<corecmsfoodordering>();
            List<UAddFoodItemInfo> infos = new List<UAddFoodItemInfo>();
            foreach (var ctrl in this.GetControls<UIAddFoodsItem>(true))
            {
                int id = CommFunc.ConvertToInt32(ctrl.Tag);
                int count = ctrl.Count;
                var packdetail = packdetailList.Find(p => p.rowId == id);
                packdetail.itemCount = count;
            }
            string strMsg = "";
            if (!string.IsNullOrEmpty(strMsg))
                if (!ShowAskDialog(strMsg)) return;

            orderingParent.sourceId = (long)YitIdHelper.NextId();
            var foodorderingList = new List<corecmsfoodordering> { orderingParent };
            int rowId = orderingParent.rowId;
            foreach (var item in packdetailList)
            {
                if (item.itemCount > 0)
                {
                    rowId++;
                    item.orderId = orderingParent.orderId;
                    item.sourceId = orderingParent.sourceId;
                    item.billerId = AppConstVars.sysUser.id;
                    item.rowId = rowId;
                    item.quantity = item.itemCount * item.foodPackQuantity;
                    item.foodPackQuantity = item.quantity;
                    item.amount = item.quantity * item.price;
                    item.realAmount = item.quantity * item.price;
                    item.allAmount= item.quantity * item.price; 
                    item.itemType = (int)GlobalEnumVars.FoodType.GroupChild;

                    foodorderingList.Add(item);
                }
            }

            var bl = new corecmsfoodorderingServices().InsertRange(foodorderingList);
            if (!bl)
            {
                UIMessageBox.Show("保存失败。", "系统出错-SaveOrderingFeed:", UIStyle.Orange, UIMessageBoxButtons.OK);
                return;
            }
            this.DialogResult = System.Windows.Forms.DialogResult.OK;

        }
    }
}
